package cn.itcast.travel.service.impl;

import cn.itcast.travel.dao.CategoryDao;
import cn.itcast.travel.dao.impl.CategoryDaoImp;
import cn.itcast.travel.domain.Category;
import cn.itcast.travel.service.CategoryService;
import cn.itcast.travel.util.JedisUtil;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Tuple;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public class CategoryServiceImp implements CategoryService {
    private CategoryDao categoryDao=new CategoryDaoImp();
    @Override
    public List<Category> findAll() {
        Jedis jedis = JedisUtil.getJedis();
        Set<Tuple> category = jedis.zrangeWithScores("category", 0, -1);
        List<Category> all=null;
        if (category==null||category.size()==0){
             all = categoryDao.findAll();
            for (int i = 0; i <all.size(); i++) {
                jedis.zadd("category",all.get(i).getCid(),all.get(i).getCname());
            }
        }else {
            all=new ArrayList<Category>();
            for (Tuple tuple:category){
                Category category1=new Category();
                category1.setCname(tuple.getElement());
                category1.setCid((int)tuple.getScore());
                all.add(category1);
            }
        }
        jedis.close();
        return all;
    }
}
